# -*- coding:utf-8 -*-
"""
@time       2016/12/07 下午5:30
"""
from sympy import degree, solveset
from mathsolver.functions.base import *


# 二项展开式，对应每一个结果


class ExsAllCoeffs(BaseFunction):
    def solver(self, *args):  # in: BaseEq, 左边为一般式，右边为展开式
        left, right = args[0].sympify()
        pl = (left - right).expand()
        max_dg = degree(pl)
        cds = []
        sym = left.free_symbols.pop()
        while max_dg:
            ce = pl.coeff(sym ** max_dg)
            cds.append(ce)
            pl -= ce * sym ** max_dg.expand()
            max_dg -= 1
        p = simplify(pl)
        if p != 0:
            cds.append(p)
        result = solve(cds, dict=True)[0]
        sym_val = BaseSymbolValue(result)
        self.steps.append(["", "求得：%s" % sym_val.printing()])
        self.output.append(sym_val)
        return self


class ExsCompute(BaseFunction):  # 计算系数多项式，如:a_{1}+a_{2}+a_{3}+a_{4}=()
    def solver(self, *args):  # in:poly
        poly = args[0].sympify()
        if poly.is_Add:
            poly_item = poly.args
        else:
            poly_item = [poly]
        for item in poly_item:
            rs = self.search(item).args[0]
            if rs:
                poly = poly.subs({item: rs})
        poly = BaseValue(poly)
        self.steps.append(["", "结果为:%s" % poly.printing()])
        self.output.append(poly)
        return self


class ExsComputerEq(BaseFunction):  # 计算等式中的未知数
    def solver(self, *args):  # in: left, right
        left = args[0].sympify()
        right = args[1].sympify()
        ply = left - right
        sym = ply.free_symbols.pop()
        rst = solveset(ply, domain=S.Reals)
        result = {sym: rst}
        sym_val = BaseSymbolValue(result)
        self.steps.append(["", "解得：%s" % sym_val.printing()])
        self.output.append(sym_val)
        return self


if __name__ == '__main__':
    pass
